<template>
  <div class="page-container" id="Product">
    <el-space>
      <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
      <el-input
        v-model="searchParams.keyStr"
        placeholder="类型名称"
        style="margin-right: 10px"
      />
      <el-button type="primary" :icon="Search" @click="handleSearch"
        >搜索</el-button
      >
      <el-button :icon="Refresh" @click="reset">重置</el-button>
      <el-button
        type="danger"
        plain
        :icon="Delete"
        :disabled="selections.length == 0"
        @click="handleDelete"
        >删除
      </el-button>
    </el-space>
    <el-table
      v-loading="loading"
      border
      :data="dataList"
      style="margin-top: 10px; min-height: 66vh"
      @selection-change="handleRowSelect"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="类型名称" prop="SeriesName" />
      <el-table-column width="220" label="图片" prop="SeriesAvatar">
        <template v-slot="{ row }">
          <div class="grid grid-cols-2" v-if="row.SeriesAvatar">
            <el-image
              v-for="(item, i) in row.SeriesAvatar.split(',')"
              :key="i"
              style="width: 100px; height: 100px"
              :src="item"
              :preview-src-list="row.SeriesAvatar.split(',')"
              preview-teleported
              hide-on-click-modal
              fit="contain"
            ></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品类目" prop="ProductTypeName" />
      <el-table-column label="商品品牌" prop="BrandName" />
      <el-table-column
        label="参考价"
        prop="RecommandPrice"
        :formatter="
          (r) =>
            r.RecommandPrice ? `￥${JSON.stringify(r.RecommandPrice)}` : 0
        "
      />
      <el-table-column label="商品推荐" prop="RecommandLevel" />
      <el-table-column label="销量" prop="SalesVolume" />
      <el-table-column width="240" label="操作">
        <template v-slot="{ row }">
          <el-button link type="primary" @click="handleOpenEdit(row)"
            >编辑</el-button
          >
          <el-button @click="handleDelete(row.SeriesId)" link type="danger"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="searchParams.total > 0"
      :total="searchParams.total"
      v-model:page="searchParams.pageNum"
      v-model:limit="searchParams.pageSize"
      @pagination="getData"
    />
    <ProductEditModal
      :open="open"
      :isUpdate="isUpdate"
      :data="currentData"
      @reload="reload"
      @closeModal="open = false"
    />
  </div>
</template>
<script setup>
import { Plus, Refresh, Search, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import ProductEditModal from "./components/ProductEditModal.vue";
import useOrderAttrStore from "@/store/modules/orderAttrs";
import { createUniqueString } from "@/utils";
import {
  seriesQueryApi,
  seriesUpdateApi,
  seriesRemoveApi,
} from "@/api/order/series/index.js";
import {
  attrQueryApi,
  attrUpdateApi,
  attrRemoveApi,
} from "@/api/order/attr/index.js";
import { uploadImg } from "@/api/upload.js";

defineOptions({ name: "Product" });
const router = useRouter();
const dataList = ref([]);
const open = ref(false);
const isUpdate = ref(false);
const currentData = ref({});
const loading = ref(false);
const searchParams = ref({
  keyStr: "",
  pageNum: 1,
  pageSize: 10,
  total: 10,
});
const selections = ref([]);
const orderStore = useOrderAttrStore();
async function getData() {
  loading.value = true;
  const res = await seriesQueryApi(searchParams.value);
  searchParams.value.total = res.TotalCount;
  if (res.Count > 0) {
    dataList.value = res.Data;
  }
  loading.value = false;
}
function handleOpenEdit(data) {
  isUpdate.value = true;
  open.value = true;
  currentData.value = data;
}
function handleDelete(id) {
  ElMessageBox.confirm("确认删除？", "提示", {
    type: "warning",
  })
    .then(async (res) => {
      if (searchParams.value.total > 1) {
        if (typeof id == "number") await seriesRemoveApi([id]);
        else await seriesRemoveApi(selections.value.map((e) => e.SeriesId));
        if (orderStore.currentProductSeries.SeriesId == id)
          orderStore.setCurrentSeries(dataList.value[0].SeriesId);
        ElMessage.success("删除成功");
        getData();
      } else {
        ElMessage.warning("至少保留一条数据");
      }
    })
    .catch(() => {});
}
function handleAdd() {
  isUpdate.value = false;
  open.value = true;
}
async function reload(data, update) {
  searchParams.value.keyStr = "";
  if (update) {
    if (data.SeriesAvatar && !data.SeriesAvatar.includes("https://")) {
      const response = await fetch(data.SeriesAvatar);
      const blob = await response.blob();
      let urlResponse = await uploadImg({
        PictureType: 2,
        Name: data.SeriesName,
        img: new File([blob], data.SeriesImgName, {
          type: blob.type,
        }),
      });
      data.SeriesAvatar = urlResponse.name;
    }
    const res = await seriesUpdateApi(data);
    if (res.IsSuccess) {
      ElMessage.success("修改成功");
      getData();
    }
  } else {
    const res = await seriesUpdateApi(data);
    // 从非标门系列中导入属性
    if (res.IsSuccess) {
      await getData();
      loading.value = true;
      await setAttrData(data.SeriesName);
      ElMessage.success("新增成功");
      loading.value = false;
    }
  }
}
async function setAttrData(seriesName) {
  const added = dataList.value.find((item) => item.SeriesName == seriesName);
  const res1 = await attrQueryApi({ seriesId: 1, pageSize: 100 });
  for (let i = 0; i < res1.Data.length; i++) {
    await attrUpdateApi({
      ...res1.Data[i],
      AttrId: 0,
      SeriesId: added.SeriesId,
    });
  }
}
function handleSearch() {
  getData();
}
function reset() {
  searchParams.value.keyStr = "";
  getData();
}
function handleRowSelect(e) {
  selections.value = e;
}
onMounted(() => {
  getData();
});
</script>

<style lang="scss" scoped>
.page-container {
  margin: 10px;
  padding: 10px;
  padding-bottom: 20px;
  border: 1px solid #ccc;
  border-radius: 2px;
}
</style>
